<template>
  <div class="production-planning">
    <!-- 页面标题和操作 -->
    <div class="page-header">
      <div class="header-left">
        <h1>生产计划管理</h1>
        <p>主生产计划(MPS)和物料需求计划(MRP)管理</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="createPlan">
          <el-icon><Plus /></el-icon>
          新建计划
        </el-button>
        <el-button @click="runMRP">
          <el-icon><Setting /></el-icon>
          运行MRP
        </el-button>
        <el-button @click="exportData">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" inline>
        <el-form-item label="计划类型">
          <el-select v-model="filterForm.planType" placeholder="请选择" clearable>
            <el-option label="主生产计划(MPS)" value="MPS" />
            <el-option label="物料需求计划(MRP)" value="MRP" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input v-model="filterForm.productName" placeholder="请输入产品名称" clearable />
        </el-form-item>
        <el-form-item label="计划状态">
          <el-select v-model="filterForm.status" placeholder="请选择" clearable>
            <el-option label="草稿" value="draft" />
            <el-option label="已发布" value="published" />
            <el-option label="执行中" value="executing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchPlans">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 计划列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>生产计划列表</span>
          <div class="header-actions">
            <el-button type="text" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="planData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="planNo" label="计划编号" width="140" />
        <el-table-column prop="planType" label="计划类型" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.planType === 'MPS' ? 'primary' : 'success'">
              {{ scope.row.planType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="产品名称" min-width="150" />
        <el-table-column prop="productCode" label="产品编码" width="120" />
        <el-table-column prop="plannedQuantity" label="计划数量" width="100" align="right" />
        <el-table-column prop="completedQuantity" label="完成数量" width="100" align="right" />
        <el-table-column prop="progress" label="进度" width="120">
          <template #default="scope">
            <el-progress :percentage="scope.row.progress" :stroke-width="8" />
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120" />
        <el-table-column prop="endDate" label="结束日期" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="scope">
            <el-tag :type="getPriorityType(scope.row.priority)">{{ scope.row.priority }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="viewPlan(scope.row)">
              查看
            </el-button>
            <el-button type="text" size="small" @click="editPlan(scope.row)">
              编辑
            </el-button>
            <el-button type="text" size="small" @click="copyPlan(scope.row)">
              复制
            </el-button>
            <el-dropdown @command="handleCommand">
              <el-button type="text" size="small">
                更多<el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{action: 'publish', row: scope.row}">
                    发布计划
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'execute', row: scope.row}">
                    执行计划
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'pause', row: scope.row}">
                    暂停计划
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'cancel', row: scope.row}" divided>
                    取消计划
                  </el-dropdown-item>
                  <el-dropdown-item :command="{action: 'delete', row: scope.row}">
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建/编辑计划对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="planFormRef"
        :model="planForm"
        :rules="planFormRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划类型" prop="planType">
              <el-select v-model="planForm.planType" placeholder="请选择计划类型">
                <el-option label="主生产计划(MPS)" value="MPS" />
                <el-option label="物料需求计划(MRP)" value="MRP" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="planForm.priority" placeholder="请选择优先级">
                <el-option label="高" value="高" />
                <el-option label="中" value="中" />
                <el-option label="低" value="低" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品" prop="productId">
              <el-select
                v-model="planForm.productId"
                placeholder="请选择产品"
                filterable
                @change="handleProductChange"
              >
                <el-option
                  v-for="product in productOptions"
                  :key="product.id"
                  :label="product.name"
                  :value="product.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划数量" prop="plannedQuantity">
              <el-input-number
                v-model="planForm.plannedQuantity"
                :min="1"
                :max="999999"
                placeholder="请输入计划数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                v-model="planForm.startDate"
                type="date"
                placeholder="请选择开始日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                v-model="planForm.endDate"
                type="date"
                placeholder="请选择结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="planForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="savePlan" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- MRP运算对话框 -->
    <el-dialog v-model="mrpDialogVisible" title="MRP运算" width="600px">
      <el-form :model="mrpForm" label-width="120px">
        <el-form-item label="运算范围">
          <el-radio-group v-model="mrpForm.scope">
            <el-radio label="all">全部产品</el-radio>
            <el-radio label="selected">选中产品</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="计划时间范围">
          <el-date-picker
            v-model="mrpForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="安全库存">
          <el-switch v-model="mrpForm.considerSafetyStock" />
        </el-form-item>
        <el-form-item label="在制品">
          <el-switch v-model="mrpForm.considerWIP" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="mrpDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="executeMRP" :loading="mrpRunning">
            开始运算
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Setting,
  Download,
  Search,
  Refresh,
  ArrowDown
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const mrpRunning = ref(false)
const dialogVisible = ref(false)
const mrpDialogVisible = ref(false)
const dialogTitle = ref('')
const planFormRef = ref(null)
const selectedPlans = ref([])

// 筛选表单
const filterForm = reactive({
  planType: '',
  productName: '',
  status: '',
  dateRange: []
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 计划表单
const planForm = reactive({
  id: null,
  planType: 'MPS',
  productId: '',
  plannedQuantity: 1,
  startDate: '',
  endDate: '',
  priority: '中',
  remark: ''
})

// MRP表单
const mrpForm = reactive({
  scope: 'all',
  dateRange: [],
  considerSafetyStock: true,
  considerWIP: true
})

// 表单验证规则
const planFormRules = {
  planType: [{ required: true, message: '请选择计划类型', trigger: 'change' }],
  productId: [{ required: true, message: '请选择产品', trigger: 'change' }],
  plannedQuantity: [{ required: true, message: '请输入计划数量', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }]
}

// 产品选项
const productOptions = ref([
  { id: 1, name: '智能手机主板', code: 'MB001' },
  { id: 2, name: '电源适配器', code: 'PA001' },
  { id: 3, name: '数据线', code: 'DC001' },
  { id: 4, name: '保护壳', code: 'PC001' },
  { id: 5, name: '耳机', code: 'HP001' }
])

// 计划数据
const planData = ref([
  {
    id: 1,
    planNo: 'MPS202501001',
    planType: 'MPS',
    productName: '智能手机主板',
    productCode: 'MB001',
    plannedQuantity: 1000,
    completedQuantity: 750,
    progress: 75,
    startDate: '2025-01-15',
    endDate: '2025-01-25',
    status: 'executing',
    priority: '高',
    remark: '紧急订单'
  },
  {
    id: 2,
    planNo: 'MRP202501001',
    planType: 'MRP',
    productName: '电源适配器',
    productCode: 'PA001',
    plannedQuantity: 500,
    completedQuantity: 200,
    progress: 40,
    startDate: '2025-01-18',
    endDate: '2025-01-28',
    status: 'executing',
    priority: '中',
    remark: '常规生产'
  },
  {
    id: 3,
    planNo: 'MPS202501002',
    planType: 'MPS',
    productName: '数据线',
    productCode: 'DC001',
    plannedQuantity: 2000,
    completedQuantity: 2000,
    progress: 100,
    startDate: '2025-01-10',
    endDate: '2025-01-20',
    status: 'completed',
    priority: '中',
    remark: '已完成'
  },
  {
    id: 4,
    planNo: 'MRP202501002',
    planType: 'MRP',
    productName: '保护壳',
    productCode: 'PC001',
    plannedQuantity: 800,
    completedQuantity: 0,
    progress: 0,
    startDate: '2025-01-22',
    endDate: '2025-02-01',
    status: 'published',
    priority: '低',
    remark: '待执行'
  }
])

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    draft: 'info',
    published: 'warning',
    executing: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    draft: '草稿',
    published: '已发布',
    executing: '执行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 获取优先级类型
const getPriorityType = (priority) => {
  const priorityMap = {
    '高': 'danger',
    '中': 'warning',
    '低': 'info'
  }
  return priorityMap[priority] || 'info'
}

// 事件处理函数
const searchPlans = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    loading.value = false
    ElMessage.success('查询完成')
  }, 1000)
}

const resetFilter = () => {
  Object.assign(filterForm, {
    planType: '',
    productName: '',
    status: '',
    dateRange: []
  })
  searchPlans()
}

const refreshData = () => {
  searchPlans()
}

const createPlan = () => {
  dialogTitle.value = '新建生产计划'
  resetPlanForm()
  dialogVisible.value = true
}

const editPlan = (row) => {
  dialogTitle.value = '编辑生产计划'
  Object.assign(planForm, {
    id: row.id,
    planType: row.planType,
    productId: getProductIdByName(row.productName),
    plannedQuantity: row.plannedQuantity,
    startDate: row.startDate,
    endDate: row.endDate,
    priority: row.priority,
    remark: row.remark
  })
  dialogVisible.value = true
}

const viewPlan = (row) => {
  ElMessage.info(`查看计划：${row.planNo}`)
}

const copyPlan = (row) => {
  dialogTitle.value = '复制生产计划'
  Object.assign(planForm, {
    id: null,
    planType: row.planType,
    productId: getProductIdByName(row.productName),
    plannedQuantity: row.plannedQuantity,
    startDate: '',
    endDate: '',
    priority: row.priority,
    remark: row.remark
  })
  dialogVisible.value = true
}

const handleCommand = (command) => {
  const { action, row } = command
  switch (action) {
    case 'publish':
      ElMessage.success(`发布计划：${row.planNo}`)
      break
    case 'execute':
      ElMessage.success(`执行计划：${row.planNo}`)
      break
    case 'pause':
      ElMessage.warning(`暂停计划：${row.planNo}`)
      break
    case 'cancel':
      ElMessageBox.confirm('确定要取消此计划吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ElMessage.success(`取消计划：${row.planNo}`)
      })
      break
    case 'delete':
      ElMessageBox.confirm('确定要删除此计划吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ElMessage.success(`删除计划：${row.planNo}`)
      })
      break
  }
}

const handleSelectionChange = (selection) => {
  selectedPlans.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  searchPlans()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  searchPlans()
}

const handleDialogClose = () => {
  resetPlanForm()
}

const handleProductChange = (productId) => {
  // 根据产品变化更新相关信息
  console.log('Selected product:', productId)
}

const savePlan = () => {
  planFormRef.value.validate((valid) => {
    if (valid) {
      saving.value = true
      // 模拟API调用
      setTimeout(() => {
        saving.value = false
        dialogVisible.value = false
        ElMessage.success(planForm.id ? '更新成功' : '创建成功')
        searchPlans()
      }, 1000)
    }
  })
}

const runMRP = () => {
  mrpDialogVisible.value = true
}

const executeMRP = () => {
  mrpRunning.value = true
  // 模拟MRP运算
  setTimeout(() => {
    mrpRunning.value = false
    mrpDialogVisible.value = false
    ElMessage.success('MRP运算完成')
  }, 3000)
}

const exportData = () => {
  ElMessage.success('导出功能开发中')
}

// 辅助函数
const resetPlanForm = () => {
  Object.assign(planForm, {
    id: null,
    planType: 'MPS',
    productId: '',
    plannedQuantity: 1,
    startDate: '',
    endDate: '',
    priority: '中',
    remark: ''
  })
  planFormRef.value?.clearValidate()
}

const getProductIdByName = (name) => {
  const product = productOptions.value.find(p => p.name === name)
  return product ? product.id : ''
}

// 生命周期
onMounted(() => {
  searchPlans()
  pagination.total = planData.value.length
})
</script>

<style scoped>
.production-planning {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-left p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.filter-card,
.table-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .production-planning {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-right {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .el-form--inline .el-form-item {
    display: block;
    margin-right: 0;
    margin-bottom: 16px;
  }
}
</style>